<?php

namespace yunj\app\admin\service\member\log;

use yunj\app\admin\job\AdminMemberLogRecordJob;

class LogRecordService extends Service {

    /**
     * 处理记录日志并返回日志数据
     * @param array $appendArgs 补充参数，如：['data_id'=>999,'desc'=>'描述']
     * @return array
     */
    public static function handle(array $appendArgs = []): array {
        $log = [];
        $adminRouteRequestData = request()->adminRouteRequestData;
        try {
            if (!$adminRouteRequestData || !self::isRecord()) {
                return $log;
            }
            $log = request()->log;
            if (!$log) {
                $log = [
                    'id' => snowflake_next_id(),
                    'request_id' => $adminRouteRequestData['id'],
                    'method' => request_method(),
                    'ip' => request_ip(),
                    'create_time' => time(),
                    'user_agent' => request()->header('user-agent'),
                    'query_string' => request()->query(),
                    'request_params' => json_encode(request()->all(), JSON_UNESCAPED_UNICODE),   // 防止文件类型参数，base64等自行调整路由日志记录配置
                ];
            }
            // member_id
            if ($appendArgs['member_id'] ?? '') {
                $log['member_id'] = $appendArgs['member_id'];
            }
            if (!array_key_exists('member_id', $log)) {
                $log['member_id'] = self::getCurrMemberId();
            }
            // data_id
            if ($appendArgs['data_id'] ?? '') {
                $log['data_id'] = $appendArgs['data_id'];
            }
            // desc
            if ($appendArgs['desc'] ?? '') {
                $log['desc'] = $appendArgs['desc'];
            }
            // response_content
            if ($appendArgs['response_content'] ?? '') {
                $log['response_content'] = $appendArgs['response_content'];
            }

            request()->log = $log;
            \think\facade\Queue::push(AdminMemberLogRecordJob::class, $log);
        } catch (\Throwable $e) {
            log_exception($e, '', "admin log recoed fail!");
        }
        return $log?:[];
    }

    /**
     * 获取当前操作的成员id
     * @return int
     */
    private static function getCurrMemberId(): int {
        $member = admin_member_login_service()->validate();
        return $member ? (int)$member->id : 0;
    }

    /**
     * 是否记录
     * @return bool
     */
    private static function isRecord(): bool {
        static $res;
        if (!is_null($res)) {
            return $res;
        }
        // 默认true
        $res = true;
        $isRecordCall = yunj_config('log.is_record');
        if (is_callable($isRecordCall)) {
            $_res = call_user_func($isRecordCall);
            if (is_bool($_res)) {
                $res = $_res;
            }
        }
        return $res;
    }

}